import { createRouter, createWebHistory } from 'vue-router'
const routes = [
  {
    path: "/",
    redirect: "/login"
  },
  {
    path: "/index",
    component: () => import('../views/index.vue'),
    children: [
      {
        path: 'product',
        component: () => import('../views/product.vue')
      },
      {
        path: 'shop',
        component: () => import('../views/shop.vue')
      },
      {
        path: 'userlist',
        component: () => import('../views/userList.vue')
      },
      {
        path: 'withdrawal',
        component: () => import('../views/withdrawal.vue')
      },
      {
        path: 'marquee',
        component: () => import('../views/marquee.vue')
      },
      // 过滤器
      {
        path: '/:pathMatch(.*)',
        component: () => import('../views/login.vue')
      },
      {
        path: 'typelist',
        name: 'typelist',
        component: () => import('../views/TypeList.vue')
      }, {
        path: 'marketorders',
        name: 'marketorders',
        component: () => import('../views/MarketOrders.vue')
      },
      {
        path: 'artorders',
        name: 'artorders',
        component: () => import('../views/ArtOrders.vue'),
      },
      {
        path: 'pay',
        name: 'pay',
        component: () => import('../views/pay.vue')
      },

    ]
  },
  {
    path: "/login",
    component: () => import('../views/login.vue')
  }, {
    path: "/register",
    component: () => import('../views/register.vue')
  }
]



const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  linkActiveClass: 'active'
})

router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token');
  
  if (token) {
    // 如果存在 token，则放行，进入目标路由
    next();
  } else if (to.path === '/login') {
    // 如果不存在 token，但前往的是登录页，则允许进入
    next();
  } else {
    // 否则强制跳转至登录页
    next('/login');
  }
})

export default router
